package com.project.config;

import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;

/**
 * EhCache缓存配置类
 * 动态添加缓存参考：http://blog.csdn.net/u012255097/article/details/54576720
 */
@Configuration
public class EhcacheConfig {

    @Bean
    @Primary //配置了多个CacheManager，指定一个CacheManager作为默认
    public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean) { // 此错误提示可忽略，程序可正常运行

        EhCacheCacheManager ehCacheCacheManager=new EhCacheCacheManager(bean.getObject());

        /**
         * 也可在此动态添加缓存，这样就可以动态配置缓存的参数
         */

        //创建一个缓存管理器
        //CacheManager singletonManager = CacheManager.create();
        //建立一个缓存实例
        //Cache cache = new Cache("demo", 5000, false, false, 300, 300);
        //在内存管理器中添加缓存实例
        //ehCacheCacheManager.getCacheManager().addCache(cache);

        return ehCacheCacheManager;
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("config/ehcache.xml"));
        cacheManagerFactoryBean.setShared(true);

        return cacheManagerFactoryBean;
    }

}